package patterndesign.compositepattern;

import java.util.ArrayList;
import java.util.List;

abstract class Node {
    private final String name;

    public Node(String name) {
        this.name = name;
    }


    public void print() {
        System.out.println(name);
    }
}

class LeafNode extends Node {

    public LeafNode(String name) {
        super(name);
    }

}

class BranchNode extends Node {

    List<Node> nodes = new ArrayList<>();

    public BranchNode(String name) {
        super(name);
    }

    public void add(Node node) {
        nodes.add(node);
    }


}

public class Main {
    public static void main(String[] args) {
        // 组织树状结构
        BranchNode root = new BranchNode("root");

        BranchNode ch1 = new BranchNode("ch1");
        BranchNode ch2 = new BranchNode("ch2");

        LeafNode c11 = new LeafNode("c11");
        LeafNode c12 = new LeafNode("c11");

        BranchNode section1 = new BranchNode("section1");
        LeafNode c21 = new LeafNode("c21");
        LeafNode c22 = new LeafNode("c22");

        // 组装
        root.add(ch1);
        root.add(ch2);

        ch1.add(c11);
        ch1.add(c12);

        ch2.add(section1);

        section1.add(c21);
        section1.add(c22);
        tree(root,0);

    }

    public static void tree(Node node, int depth) {
        for (int i = 0; i < depth; i++) {
            System.out.print("--");
        }
        node.print();

        if (node instanceof BranchNode) {
            for (Node b : ((BranchNode) node).nodes) {
                tree(b, depth + 1);
            }
        }
    }
}
